package com.lxq.live.wetsocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@ServerEndpoint("/socket/video/{video_uuid}")
@Component
public class VideoSocketServer {

    private static int initNumber = 0;
    private static ConcurrentMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(@PathParam("video_uuid") String uuid, Session session) {
        initNumber++;
        System.out.println("initNumber is=" + initNumber);
        System.out.println("connection event append in OnMessage，uuid=" + uuid + "，and session's id="
                + session.getId() + "，size=" + sessionMap.size());
        sessionMap.put(session.getId(), session);
        sessionMap.forEach((index, item) -> {
            System.out.println("index=" + index);
            try {
                item.getBasicRemote().sendText("来自服务器的消息：" + session.getId() + "来了");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    @OnMessage
    public void onMessage(String msg, Session session) {
        initNumber++;
        System.out.println("initNumber is=" + initNumber);
        sessionMap.forEach((index, item) -> {
            try {
                item.getBasicRemote().sendText("来自" + session.getId() + "的消息：" + msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println(session.getId()+" 退出断开连接");
        sessionMap.remove(session.getId());
        sessionMap.forEach((index, item) -> {
            try {
                item.getBasicRemote().sendText("来自" + session.getId() + "的消息：" + session.getId() + "退出了群聊");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
